// uni.setStorageSync('baseUrl', BASE_URL)
import Vue from 'vue'
import base from '@/common/config';
import vuex from '@/store';
import {router,RouterMount} from '@/router'  
const BASE_URL = base.baseUrl //智慧校园
const CONSUME_Url = base.consumeUrl //消费
let throttleBool = false
import {getOpenidApi} from '@/common/api/commonApi/commonApi.js'
export default async (params) => {
	
	if(!params.noLoading){
		// 加载中
		uni.showLoading({
		    title: '加载中'
		})
	}
  
	let currentUrl = ''
	if(params.isConsume){
		currentUrl = CONSUME_Url
	}else{
		currentUrl = BASE_URL
	}
  
	let defaultData ={}
	if(params.isOpenId){
		// #ifdef MP-WEIXIN
			defaultData.openId = uni.getStorageSync('openId')
		// #endif
	}
	if(params.isOaopenId){
		// #ifdef H5
			defaultData.oaopenId = uni.getStorageSync('oaopenid')
		// #endif
	}
	Object.assign(defaultData,params.data)

    return new Promise(async(resolve, reject) => {
		
		// #ifdef MP-WEIXIN
		if(params.isOpenId && !defaultData.openId){
			let code = ''
			await getwxCode().then( res=>{
				code = res
			})
			await getOpenidApi({
				js_code : code
			}).then( res=>{
				defaultData.openId = res.result.openid
				uni.setStorageSync('openId',defaultData.openId )
				uni.setStorageSync('unionid',res.result.unionid )
			})
		}
		// #endif
		
		let header = {
			'Content-Type':  'application/json',
			// 'Content-Type': 'application/x-www-form-urlencoded' ,
		}
		if(params.isToken){
			// header.token = uni.getStorageSync('token')
			// header.Authorization = uni.getStorageSync('token')
			header['X-Access-Token'] = uni.getStorageSync('token')
			// header['X-Access-Token'] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MjEzOTYwNjUsInVzZXJuYW1lIjoiMjQwNTEyMDEifQ.AjN9aVgXRyid9ud9KGhsVIMMbAOqfZnBnc0J-YZlye0'
			header['X-Tenant-Id'] =  uni.getStorageSync('X-Tenant-Id')
			// header['X-Tenant-Id'] =  1000
		}
		
        uni.request({
            ...params,
            url: currentUrl + params.url,
            method: params.method || 'POST',
            // data: params.data || {},
            data: defaultData,
            dataType: "json",
            header,
            success(res) {
				uni.hideLoading()
				
				if(res.data.message=='token失效，请重新登录'){
					let title = res.data.message ? res.data.message : res.data.msg
					uni.showToast({
					    title,
					    duration: 3000,
					    icon: 'none',
						success: () => {
						}
					});
					// once(()=>{
					// 	uni.showToast({
					// 	    title: '登录失效，正在重新登录',
					// 	    duration: 3000,
					// 	    icon: 'none',
					// 		success: () => {
					// 		}
					// 	});
					// 	setTimeout(()=>{
					// 		uni.reLaunch({
					// 			url: '/pages/index/index'
					// 		})
					// 	},1500)
					// })()
				}else if(res.data.success == '成功获取'  || res.data.code == '200' || res.data.status=='200'|| res.data.result==1||res.data.success == true|| res.data.code == '00'){
					return resolve(res.data)
				}else{
					reject(res.data)
					let title = res.data.message ? res.data.message : res.data.msg
					uni.showToast({
					    title,
					    duration: 3000,
					    icon: 'none',
						success: () => {
						}
					});
				}
				
            },
            fail(err) {
				uni.hideLoading()
                uni.showToast({
                    title: '服务器错误',
                    duration: 3000,
                    icon: 'none',
					success: ()=>{
							reject(err)
					}
                });
				
            },
            complete() {
               
            }
        })
    })
}

function getwxCode() {
	return new Promise((resolve, reject)=>{
		wx.login({
			success(res) {
				let code = res.code
				resolve(code)
			},
		})
	})
}

function once(fn) {
    let caller = true;
    return function() {
        if(caller) {
            caller = false
            fn.apply(this, arguments)
        }
    }
    
}
